<?php

namespace catchAdmin\phone\model;

use catchAdmin\model\Notice;
use catchAdmin\model\wechat\PaymentApp;
use catchAdmin\model\WechatUserPayment;
use catcher\exceptions\AlertErrorException;
use think\facade\Config;

class WechatUserBalance extends \catchAdmin\model\WechatUserBalance
{

    /**
     * 充值
     */
    public function rechargeBalance($param)
    {
        $wechat_user_msg = (new \catchAdmin\model\WechatUser())
            ->where('id', $this->getLoginId())
            ->find();

        $trade_type_int = $param['trade_type'] ?? 1;
        // 1.公众号
        if ($trade_type_int == 1) {
            $app_id = Config::get("wechat.FuWuHaoApp.app_id");
            $openid = $wechat_user_msg['openid'];
            // 2.小程序
        } elseif ($trade_type_int == 2) {
            $app_id = Config::get("wechat.MiniProgramApp.app_id");
            $openid = $wechat_user_msg['mini_openid'];
        } else {
            throw new AlertErrorException('参数异常');
        }

        $this->startTrans();

        $zeng_value = 0;
        // 判断充值参数
        if (!empty($param['recharge_id'])) {
            $recharge_config = (new \catchAdmin\model\WechatUserBalance())->getRechargeBalanceConfig($param['recharge_id']);
            if (empty($recharge_config)) {
                throw new AlertErrorException('参数异常');
            }

            if (mathComp($recharge_config['value'], $param['total_fee']) != 0) {
                throw new AlertErrorException('参数异常');
            }
            $zeng_value = $recharge_config['zeng_value'];
        }

        $payment_msg = (new WechatUserPayment())->saveDataCC([
            'mch_id' => Config::get("wechat.PaymentApp.mch_id"),
            'app_id' => $app_id,
            'openid' => $openid,

            'wechat_user_id' => $this->getLoginId(),
            'out_trade_no'   => time() . rand(1000, 9999),
            'body'           => '充值' . $param['total_fee'],
            'total_fee'      => $param['total_fee'],
            'zeng_value'     => $zeng_value,
            'trade_type_int' => $trade_type_int,
            'trade_type'     => "JSAPI",
            'balance_type'   => 1,
            'balance_type_2' => 101,
        ]);

        $pay_send = (new PaymentApp($app_id))->payInit([
            'trade_type'   => $payment_msg['trade_type'],
            'body'         => $payment_msg['body'],
            'out_trade_no' => $payment_msg['out_trade_no'],
            'total_fee'    => $payment_msg['total_fee'],
            'notify_url'   => '/Notify/rechargeBalance',
            'openid'       => $openid,
        ]);

        $payment_msg->pay_send = json_encode($pay_send);
        $payment_msg->save();

        $this->commit();

        return $pay_send;
    }


    /**
     * 提现
     */
    public function withdrawIncome($param)
    {
        $bank_msg = (new \catchAdmin\model\WechatUserBank())
            ->where('id', $param['wechat_user_bank_id'])
            ->find();
        if (empty($bank_msg)) {
            throw new AlertErrorException('参数不正确');
        }

        $this->startTrans();

        if ($param['num'] < 100) {
            throw new AlertErrorException('提现至少100元');
        }

        (new \catchAdmin\model\WechatUserBalance())->saveWechatUserBalance([
            'wechat_user_id' => $this->getLoginId(),
            'balance_type'   => 3,
            'balance_type_2' => 302,
            'num'            => $param['num'],
            'balance_status' => 1,

            'out_trade_no' => time() . rand(1000, 9999),

            'wechat_user_bank_id' => $bank_msg['id'],
            'bank_name'           => $bank_msg['bank_name'],
            'bank_kai_name'       => $bank_msg['bank_kai_name'],
            'bank_no'             => $bank_msg['bank_no'],
        ]);

        // 2.发消息
        (new Notice())->saveDataCC([
            // 提现审核——待审核
            'notice_type'    => 2,
            'title'          => '待审核',
            'content'        => "等待后台审核",
            'wechat_user_id' => $this->getLoginId(),
        ]);

        $this->commit();

        return 1;
    }


    ######################################## 显示 ################################################

    public function indexData($param)
    {
        if (empty($param['balance_type'])) {
            $param['balance_type'] = 1;
        }

        $this_app = $this
            ->where('balance_type', $param['balance_type'])
            ->where('wechat_user_id', $this->getLoginId())
            ->order('id', 'desc');

        if (!empty($param['startDate'])) {
            $this_app = $this_app->whereTime('created_at', '>=', strtotime($param['startDate'] . ' 00:00:00'));
        }
        if (!empty($param['endDate'])) {
            $this_app = $this_app->whereTime('created_at', '<=', strtotime($param['endDate'] . ' 23:59:59'));
        }

        $msg = parent::indexDataCC($param, $this_app); // TODO: Change the autogenerated stub

        // 余额
        if ($param['balance_type'] == 1) {
            $msg['balance'] = (new \catchAdmin\model\WechatUser())
                ->where('id', $this->getLoginId())
                ->value('balance') ?? 0;
            // 积分
        } elseif ($param['balance_type'] == 2) {
            $msg['ji_fen'] = (new \catchAdmin\model\WechatUser())
                ->where('id', $this->getLoginId())
                ->value('ji_fen') ?? 0;
            // 收入
        } elseif ($param['balance_type'] == 3) {
            $msg['income'] = (new \catchAdmin\model\WechatUser())
                ->where('id', $this->getLoginId())
                ->value('income') ?? 0;
        }

        return $msg;
    }


    public function indexType($param)
    {
        $list = [];
        // 余额
        if ($param['balance_type'] == 1) {
            $list = (new WechatUserBalance())->getBalanceType2NameBalanceList();
            // 积分
        } elseif ($param['balance_type'] == 2) {
            $list = (new WechatUserBalance())->getBalanceType2NameJiFenList();
            // 佣金
        } elseif ($param['balance_type'] == 3) {
            $list = (new WechatUserBalance())->getBalanceType2NameIncomeList();
        }

        $type2_list = [];
        foreach ($list as $k => $v) {
            $type2_list[] = [
                'id'   => $k,
                'name' => $v,
            ];
        }

        return $type2_list;
    }


    /**
     * 充值列表
     */
    public function indexRechargeBalance()
    {
        return $this->getRechargeBalanceList();
    }

}
